package com.guigu.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.guigu.bean.Msg;
import com.guigu.bean.Record;
import com.guigu.service.RecordServices;

/**
 * @author 执子一白
 *处理日程的CRUD请求
 */
@Controller
public class RecordController {
	
	@Autowired
	RecordServices recordServices;
	
	/**
	 * 日程通过日期,用户ID模糊查询，注意格式为(2017-09-29)
	 * @param vagueDate
	 * @return
	 */
	@RequestMapping("/findrecords")
	@ResponseBody
	public Msg getRecordsByVagueDate(String vagueDate,@RequestParam(defaultValue="0")int userId){
		List<Record> list= recordServices.getRecordsByVagueDate(vagueDate,userId);
		if (list!=null&&!list.isEmpty()) {
			return Msg.success().add("records", list);
		}else {
			return Msg.fail().add("failInfo", "未查询到日程");
		}
	}
	
	/**
	 * 添加日程函数(唯一限制--需要传入userid,以及发送post请求)
	 * @param record
	 * @param result
	 * @return
	 */
	@RequestMapping(value="/recordCRUD",method=RequestMethod.POST)
	@ResponseBody
	public Msg saveRecord(@Valid Record record,BindingResult result){
		if (record==null||record.getUserid()==null) {
			return Msg.fail().add("failInfo", "用户ID不可为空");
		}
		
		if (result.hasErrors()) {
			Map<String, Object> map =new HashMap<String, Object>();
			List<FieldError> errors =result.getFieldErrors();
			for (FieldError fieldError : errors) {
				System.out.println("错误字段名"+fieldError.getField());
				System.out.println("错误信息"+fieldError.getDefaultMessage());
				map.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			System.out.println("进入函数");
			return Msg.fail().add("errorFields", map).add("addStatus", "添加失败");
		}else {
			recordServices.saveRecord(record);
			return Msg.success().add("addStatus", "添加成功");
		}
	}
	
	/**
	 * 日程修改功能
	 * @param record
	 * @return
	 */
	@RequestMapping(value="/recordCRUD/{recordid}",method=RequestMethod.PUT)
	@ResponseBody
	public Msg updateRecord(Record record){
		System.out.println(record);
		recordServices.updateRecord(record);
		return Msg.success();
	}
	
	
	/**
	 * 日程删除功能
	 * @param recordid
	 * @return
	 */
	@RequestMapping(value="/recordCRUD/{recordid}",method=RequestMethod.DELETE)
	@ResponseBody
	public Msg deleteByRecordId(@PathVariable("recordid")Integer recordId){
		recordServices.deleteByRecordId(recordId);
		return Msg.success();
	}
}
